package com.cskaoyan.util;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.exception.CustomValidationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * @author stone
 * @date 2022/03/26 11:44
 */
public class ValidationUtil {

    public static BaseRespVo dealWithValidationResult(BindingResult bindingResult) {
        FieldError fieldError = bindingResult.getFieldError();//拿到参数错误
        String field = fieldError.getField();//成员变量名 → 请求参数名
        Object rejectedValue = fieldError.getRejectedValue(); //传入的错误的值
        String defaultMessage = fieldError.getDefaultMessage();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("请求参数")
                .append(field)
                .append("因为传入了值")
                .append(rejectedValue)
                .append("导致异常;")
                .append(defaultMessage);
        return BaseRespVo.fail(stringBuffer.toString());
    }

    public static void validateBindingResult(BindingResult bindingResult) throws CustomValidationException {
        if (bindingResult.hasFieldErrors()) {//如果有校验错误，才做校验结果的处理
            FieldError fieldError = bindingResult.getFieldError();//拿到参数错误
            String field = fieldError.getField();//成员变量名 → 请求参数名
            Object rejectedValue = fieldError.getRejectedValue(); //传入的错误的值
            String defaultMessage = fieldError.getDefaultMessage();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("请求参数")
                    .append(field)
                    .append("因为传入了值")
                    .append(rejectedValue)
                    .append("导致异常;")
                    .append(defaultMessage);
            //异常处理 👉 ExceptionHandler
            throw new CustomValidationException(stringBuffer.toString());
        }
    }
}
